/***********************************************************************************************************************
*                                                                                                                      *
* SPLASH build system v0.1                                                                                             *
*                                                                                                                      *
* Copyright (c) 2013 Andrew D. Zonenberg                                                                               *
* All rights reserved.                                                                                                 *
*                                                                                                                      *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the     *
* following conditions are met:                                                                                        *
*                                                                                                                      *
*    * Redistributions of source code must retain the above copyright notice, this list of conditions, and the         *
*      following disclaimer.                                                                                           *
*                                                                                                                      *
*    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       *
*      following disclaimer in the documentation and/or other materials provided with the distribution.                *
*                                                                                                                      *
*    * Neither the name of the author nor the names of any contributors may be used to endorse or promote products     *
*      derived from this software without specific prior written permission.                                           *
*                                                                                                                      *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES        *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR       *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE       *
* POSSIBILITY OF SUCH DAMAGE.                                                                                          *
*                                                                                                                      *
***********************************************************************************************************************/

#include "splashcore.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction

NocgenNode::NocgenNode(
		const vector<string>& scriptlines,
		unsigned int& i,
		Nocgenv2GeneratedSourceNode* node,
		string fname)
{
	char tmp[512];
	char tmp2[512];
	char garbage[512];
	int width;
	for(; i<scriptlines.size(); i++)
	{
		string line = scriptlines[i];
		
		//Look up the opcode
		sscanf(line.c_str(), "%127s", tmp);
		string sopcode(tmp);
		
		//The node name
		if(sopcode == "node")
		{
			if(2 != sscanf(line.c_str(), "node %127s %127s", tmp, tmp2))
				FatalError("Bad node line in node block of nocgen file \"%s\"\n", line.c_str(), fname.c_str());
			m_name = tmp;
			m_module = tmp2;
		}
		
		else if(sopcode == "rpc")
			m_rpc = true;
		else if(sopcode == "dma")
			m_dma = true;
		
		else if(sopcode == "constrain")
		{
			if(2 != sscanf(line.c_str(), "constrain %127s freq %127s", tmp, tmp2))
				FatalError("Bad \"constrain\" line \"%s\" in node block of nocgen file \"%s\"", line.c_str(), fname.c_str());
				
			//Parse out the frequency
			float ffreq;
			char fmult;
			if(2 != sscanf(tmp2, "%f%c", &ffreq, &fmult))
				FatalError("Bad clock frequency \"%s\" in nocgen file \"%s\"\n", tmp2, fname.c_str());
			if(fmult == 'M')
				ffreq *= 1000000;
			else
				FatalError("Bad clock frequency \"%s\" in nocgen file \"%s\"\n", tmp2, fname.c_str());

			string clkname = tmp;
			m_internalclocks[tmp] = NocgenClockNet(tmp, NocgenClockNet::CLOCK_GLOBAL, ffreq);
		}
			
		else if(sopcode == "floorplan")
		{
			if(1 != sscanf(line.c_str(), "floorplan %127s", tmp))
				FatalError("Bad floorplan line in node block of nocgen file \"%s\"\n", line.c_str(), fname.c_str());
			m_floorplans.push_back(tmp);
		}
		
		else if(sopcode == "hmac_key")
		{
			if(1 != sscanf(line.c_str(), "hmac_key \"%127[^\"]\"", tmp))
				FatalError("Bad hmac_key line in node block of nocgen file \"%s\"\n", line.c_str(), fname.c_str());
			
			//Generate HMAC key
			unsigned char hmac_key[64];
			CryptoPP::SHA512().CalculateDigest(hmac_key, (unsigned char*)tmp, strlen(tmp));
			for(int j=0; j<16; j++)
			{
				snprintf(tmp, sizeof(tmp), "HMAC_KEY_%X", j);
				snprintf(tmp2, sizeof(tmp2), "32'h%02x%02x%02x%02x",
					hmac_key[j*4] & 0xff,
					hmac_key[j*4 + 1] & 0xff,
					hmac_key[j*4 + 2] & 0xff,
					hmac_key[j*4 + 3] & 0xff);
				m_params[tmp] = tmp2;
			}
		}
		
		else if(sopcode == "subnet")
		{
			if(1 != sscanf(line.c_str(), "subnet %127d", &width))
				FatalError("Bad subnet line in node block of nocgen file \"%s\"\n", line.c_str(), fname.c_str());
			m_subnetsize = width;
		}
		
		//I/O signal
		else if(
			(sopcode == "clock") ||
			(sopcode == "input") || (sopcode == "output") || (sopcode == "inout")  ||
			(sopcode == "nc") || (sopcode == "debug") || (sopcode == "constant") )
		{
			//A clock net (special treatment required)
			if(sopcode == "clock")
			{
				if(2 != sscanf(line.c_str(), "clock %127s port %127s", tmp, tmp2))
					FatalError("Bad clock line in node block of nocgen file \"%s\"\n", line.c_str(), fname.c_str());
				
				//Verify it's a clock.
				//If it's in the BSP, but we don't have it, import it
				if(!node->IsClockNet(tmp))
				{
					if(node->IsBSPClockNet(tmp))
						node->AddClockNetFromBSP(tmp);
					else
						FatalError("Net \"%s\" does not exist or is not a clock\n", tmp);
				}
					
				//Add it
				m_ports[tmp2] = tmp;				
				continue;
			}
			
			//A constant net (special treatment required)
			else if(sopcode == "constant")
			{
				if(2 != sscanf(line.c_str(), "constant %127s port %127s", tmp, tmp2))
					FatalError("Bad constant line in node block of nocgen file \"%s\"\n", line.c_str(), fname.c_str());
				
				//Add it
				m_ports[tmp2] = tmp;
				continue;
			}
			
			//A non-connected node (special treatment required)
			else if(sopcode == "nc")
			{
				if(1 != sscanf(line.c_str(), "nc port %127s", tmp))
					FatalError("Bad nc line in node block of nocgen file \"%s\"\n", line.c_str(), fname.c_str());
					
				m_ports[tmp] = "";
				continue;
			}
			
			//I/O direction
			unsigned int dir = 0;
			if(sopcode == "input")
				dir = NocgenBSPPin::DIR_IN;
			else if(sopcode == "output")
				dir = NocgenBSPPin::DIR_OUT;
			else if(sopcode == "inout")
				dir = NocgenBSPPin::DIR_INOUT;
			else if(sopcode == "debug")
				dir = NocgenBSPPin::DIR_NC;		//not bonded outside the chip
			else
				FatalError("bad pin direction \"%s\"", sopcode.c_str());
				
			//Parse the declaration
			if(4 != sscanf(line.c_str(), "%127s %d %127s port %127s", garbage, &width, tmp, tmp2))
				FatalError("Bad I/O net line in node block of nocgen file \"%s\"\n", line.c_str(), fname.c_str());
			
			//Add the net
			m_ports[tmp2] = tmp;
			
			//TODO: Support bit selects
			if(strstr(tmp, ":") != NULL)
				FatalError("bit selects not implemented");
			
			//Import pins from the BSP		
			if(width == 1)
				node->AddPinFromBSP(tmp, dir);
			else
				node->AddBusFromBSP(tmp, width, dir);
				
			//Register it as a clock
			if( (sopcode == "debug") && (m_internalclocks.find(tmp2) != m_internalclocks.end()) )
				node->AddClockNet(tmp, m_internalclocks[tmp2]);
		}
			
		else if(sopcode == "parameter")
		{
			if(2 != sscanf(line.c_str(), "parameter %127s %511[^\n]", tmp, tmp2))
				FatalError("Bad parameter line in node block of nocgen file \"%s\"\n", line.c_str(), fname.c_str());
			
			string sparam = tmp2;
			
			//Replace variables
			sparam = str_replace("$outdir", node->GetGraph()->GetOutDir(), sparam);
				
			m_params[tmp] = sparam;
		}
		
		//Done
		else if(sopcode == "endnode")
			break;
		
		//Garbage
		else
			FatalError("Unrecognized opcode \"%s\" in node block of nocgen file \"%s\"\n",
			sopcode.c_str(), fname.c_str());
	}
}
